//
//  main.c
//  TCP服务器
//
//  Created by lu on 2024/1/7.
//

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>

#define PORT 5001
#define BACKLOG 5

int main(int argc, const char * argv[]) {
    int fd,newfd;
    char buf[BUFSIZ] = {};
    struct sockaddr_in addr;
    int port = PORT;
    if(argc < 3){
    }else{
        port = atoi(argv[2]);
    }
    printf("port = %d\n",port);
    //创建套接字。
    fd = socket(AF_INET, SOCK_STREAM, 0);
    if (fd < 0) {
        perror("socket");
        exit(0);
    }
    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    addr.sin_addr.s_addr = 0;
    if ( argv[1]) {
        if( inet_aton(argv[1], &addr.sin_addr) == 0) {
            //转化错误
            fprintf(stderr, "Invalid address\n");
            exit(EXIT_FAILURE);
        }
    }
    /*地址快速重用*/
    int flag=1,len= sizeof (int);
    if ( setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &flag, len) == -1) {
        perror("setsockopt");
        exit(1);
    }
    int ret = bind(fd, (const struct sockaddr *)&addr, sizeof(addr));
    //绑定通讯结构体
    if (ret == -1) {
        perror("bind");
        exit(0);
    }
    //设置套接字为监听模式
    if (listen(fd, BACKLOG) == -1) {
        perror("listen");
        exit(0);
    }
    //接收客户端的连接请求,生成新的用于和客户端通讯的套接字
    newfd = accept(fd, NULL, NULL);
    if (newfd < 0) {
        perror("accept");
        exit(0);
    }
    while (1) {
        //memset(buf,0,BUFSIZ);
        bzero(buf,BUFSIZ);
        printf("BUFSIZE = %d\n",BUFSIZ);
        ssize_t res = read(newfd,buf,BUFSIZ);
        if (res < 0) {
            perror("accept");
            exit(0);
        }
        else if (res == 0) {
            break;
        }else {
            printf("BUF = %s\n",buf);
        }
    }
    close(newfd);
    close(fd);
    return 0;
}
